using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Web;
using TestSystem.BLL.TestSystem;

public partial class Controls_TestTimer : System.Web.UI.UserControl
{
    private int timePerQuiz;
    public int TimePerQuiz
    {
        get { return timePerQuiz; }
        set { timePerQuiz = value; }
    }

    private string redirectPage;
    public string RedirectPage
    {
        get { return redirectPage; }
        set { redirectPage = value; }
    }

    private bool useTimer;
    public bool UseTimer
    {
        get
        {
            return ((Quiz) Session["CurrentQuiz"]).UseTimer;
        }
    }

    private Thread timer = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["TimeLeft"] == null && Session["Timer"] == null && UseTimer)
            {
                timer = new Thread(TimerStart);
                Session["TimeLeft"] = TimePerQuiz;
                Session["Timer"] = timer;
                timer.Start();
            }
        }
        if (UseTimer)
        {
            InitTimerJs();
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Timer", Session["JS"].ToString(), true);
        }
    }

    private void InitTimerJs()
    {
        var timeLeft = (int)Session["TimeLeft"];
        var js = new StringBuilder();
        js.Append("$(function(){");
        js.Append("setTimeout(function(){");
        js.Append("redirectTo('" + RedirectPage + "');}," + (timeLeft + 1) * 1000 + ");");
        js.Append("runTimer();");
        js.Append("});");
        js.Append("function runTimer(){");
        js.Append("var timer = $('.testrunner .sidebar .timer').get()[0];");
        js.Append("var i = 0;");
        js.Append("var timeLeft = " + timeLeft + ";");
        js.Append("setInterval(function(){");
        js.Append("var hours = 0;   if(parseInt((timeLeft - i)/3600) < 10){hours = '0' + parseInt((timeLeft - i)/3600);}else{hours = (parseInt((timeLeft - i)/3600));} ");
        js.Append("var minutes = 0; if(parseInt(((timeLeft - i)%3600)/60) < 10){minutes = '0' + parseInt(((timeLeft - i)%3600)/60);}else{minutes = parseInt(((timeLeft - i)%3600)/60);} ");
        js.Append("var seconds = 0; if(parseInt(((timeLeft - i)%3600)%60) < 10){seconds = '0' + parseInt(((timeLeft - i)%3600)%60);}else{seconds = parseInt(((timeLeft - i)%3600)%60);} ");
        js.Append("timer.innerHTML = hours + ' : ' + minutes + ' : ' + seconds; i++;");
        js.Append("}, 1000);}");
        Session["JS"] = js;
    }

    private void TimerStart()
    {
        for (int i = 1; i <= TimePerQuiz + 1; i++)
        {
            Thread.Sleep(1000);
            Session["TimeLeft"] = TimePerQuiz - i;
            if (Session["DataSaved"] == null)
                break;
        }
        FinishQuiz(false);
        Thread.CurrentThread.Abort();
    }

    private void FinishQuiz(bool redirect)
    {
        if (Session["DataSaved"] != null)
        {
            SaveDate();
        }
        ClearSessionVars();
        if (redirect)
        {
            HttpContext.Current.Response.Redirect(RedirectPage);
        }
    }

    private void SaveDate()
    {
        var curQuizHistory = ((QuizHistory)Session["QuizHistory"]);
        curQuizHistory.DateTimeComplete = DateTime.Now;
        QuizHistory.Add(curQuizHistory.QuizID, curQuizHistory.UserID, curQuizHistory.DateTimeStart,
                        curQuizHistory.DateTimeComplete, curQuizHistory.Scores);

        var curQuiz = Quiz.GetByQuizID(curQuizHistory.QuizID);
        if (curQuiz.SaveUserAnswers)
        {
            var answers = ((Dictionary<int, List<UserAnswer>>)Session["UserAnswers"]);
            foreach (var key in answers.Keys)
            {
                for (int i = 0; i < answers[key].Count; i++)
                {
                    UserAnswer.Add(answers[key][i].UserAnswerID, answers[key][i].UserID,
                                   curQuizHistory.QuizID, key, answers[key][i].UserAnswerBody);
                }
            }
        }
    }

    private void ClearSessionVars()
    {
        Session["TimeLeft"] = null;
        Session["Timer"] = null;
        Session["JS"] = null;
        Session["DataSaved"] = null;
        Session["CurrentQuiz"] = null;
    }
}
